<template>
  <div class="supplier-collection-page">
    <div class="page-header">
      <h2>供应商采集管理</h2>
    </div>

    <!-- 查询条件 -->
    <div class="query-area">
      <el-form :model="queryForm" inline size="small">
        <el-form-item label="供应商名称">
          <el-input
            v-model="queryForm.supplierName"
            placeholder="请输入供应商名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input
            v-model="queryForm.project"
            placeholder="请输入项目名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="审批状态">
          <el-select v-model="queryForm.approvalStatus" placeholder="请选择审批状态" clearable>
            <el-option label="未审批" value="0"></el-option>
            <el-option label="审批通过" value="1"></el-option>
            <el-option label="审批失败" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="generateJoinLink">生成链接与二维码</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="tableLoading"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" width="150" align="center"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="120" align="center"></el-table-column>
        <el-table-column prop="project" label="项目名称" width="150" align="center"></el-table-column>
        <el-table-column prop="expertiseType" label="擅长标注类型" width="120" align="center"></el-table-column>
        <el-table-column prop="totalManpower" label="总人力" width="80" align="center"></el-table-column>
        <el-table-column prop="approvalStatus" label="审批状态" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="getApprovalStatusType(scope.row.approvalStatus)">
              {{ getApprovalStatusText(scope.row.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评级" width="100" align="center">
          <template slot-scope="scope">
            <el-input
              v-if="scope.row.editing"
              v-model="scope.row.rating"
              size="small"
              placeholder="请输入评级"
            ></el-input>
            <span v-else>{{ scope.row.rating || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime | formatDateTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="scope.row.approvalStatus === '0'" type="primary" size="small" @click="handleApprove(scope.row, 1)">通过</el-button>
            <el-button v-if="scope.row.approvalStatus === '0'" type="danger" size="small" @click="handleApprove(scope.row, 2)">拒绝</el-button>
            <el-button v-if="scope.row.approvalStatus !== '0'" type="text" size="small" @click="handleEditRating(scope.row)">
              {{ scope.row.editing ? '保存' : '评级' }}
            </el-button>
            <el-button type="text" size="small" style="color: #f56c6c" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        style="margin-top: 20px; text-align: right"
      >
      </el-pagination>
    </div>

    <!-- 审批对话框 -->
    <el-dialog
      title="审批通过"
      :visible.sync="approvalDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="approvalForm"
        :model="approvalFormData"
        label-width="100px"
      >
        <el-form-item label="审批意见">
          <el-input
            v-model="approvalFormData.approvalComment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="approvalDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApproval">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- 生成链接对话框 -->
    <el-dialog
      title="供应商加盟链接"
      :visible.sync="joinLinkDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form label-width="80px">
        <el-form-item label="链接地址">
          <el-input
            v-model="joinLinkData.url"
            type="textarea"
            :rows="3"
            readonly
          ></el-input>
        </el-form-item>
        <el-form-item label="二维码">
          <div class="qrcode-container">
            <img 
              :src="'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + encodeURIComponent(joinLinkData.url)" 
              alt="二维码"
              class="qrcode-image"
            />
          </div>
        </el-form-item>
      </el-form>
    
      <div slot="footer" class="dialog-footer">
        <el-button @click="joinLinkDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="copyLink">复制链接</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getSupplierRegistrationListAPI,
  updateSupplierRegistrationAPI,
  deleteSupplierRegistrationAPI
} from '@/api/supplierRegistration';

export default {
  name: 'SupplierCollection',
  filters: {
    // 格式化日期时间
    formatDateTime(value) {
      if (!value) return '';
      return value.replace('T', ' ').substring(0, 19);
    }
  },
  data() {
    return {
      approvalDialogVisible: false,
      approvalDialogTitle: '',
      approvalFormData: {
        id: null,
        approvalStatus: null,
        approvalComment: ''
      },
      // 生成链接对话框
      joinLinkDialogVisible: false,
      joinLinkData: {
        url: '',
        qrCode: ''
      },
      // 查询表单
      queryForm: {
        supplierName: '',
        project: '',
        approvalStatus: ''
      },
      // 表格数据
      tableData: [],
      tableLoading: false,
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  mounted() {
    // 页面加载时查询数据
    this.getTableData();
  },
  methods: {
    // 查询数据
    handleQuery() {
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    
    // 重置查询
    handleReset() {
      this.queryForm = {
        supplierName: '',
        project: '',
        approvalStatus: ''
      };
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    
    // 获取表格数据
    getTableData() {
      this.tableLoading = true;
      
      // 构建查询参数
      const params = {
        currentPage: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      };
      
      if (this.queryForm.supplierName) {
        params.supplierName = this.queryForm.supplierName;
      }
      
      if (this.queryForm.project) {
        params.project = this.queryForm.project;
      }
      
      if (this.queryForm.approvalStatus) {
        params.approvalStatus = this.queryForm.approvalStatus;
      }
      
      // 调用后端接口查询数据
      getSupplierRegistrationListAPI(params).then(res => {
        this.tableLoading = false;
        if (res.code === 200) {
          this.tableData = (res.data.records || []).map(item => ({
            ...item,
            editing: false
          }));
          this.pagination.total = res.data.total || 0;
          this.pagination.currentPage = res.data.currentPage || 1;
          this.pagination.pageSize = res.data.pageSize || 10;
        } else {
          this.$message.error(res.message || '查询失败');
        }
      }).catch(error => {
        this.tableLoading = false;
        this.$message.error('查询失败，请检查网络');
        console.error('查询错误:', error);
      });
    },
    
    // 审批操作
    handleApprove(row, status) {
      this.approvalFormData.id = row.id;
      this.approvalFormData.approvalStatus = status;
      this.approvalDialogTitle = status === 1 ? '审批通过' : '审批拒绝';
      this.approvalFormData.approvalComment = '';
      this.approvalDialogVisible = true;
    },
    
    // 提交审批
    submitApproval() {
      const data = {
        approvalStatus: this.approvalFormData.approvalStatus,
        approvalComment: this.approvalFormData.approvalComment
      };
      
      updateSupplierRegistrationAPI(this.approvalFormData.id, data).then(res => {
        if (res.code === 200) {
          this.$message.success('审批操作成功');
          this.approvalDialogVisible = false;
          this.getTableData();
        } else {
          this.$message.error(res.message || '审批操作失败');
        }
      }).catch(error => {
        this.$message.error('审批操作失败，请检查网络');
        console.error('审批错误:', error);
      });
    },
    
    // 编辑评级
    handleEditRating(row) {
      if (row.editing) {
        // 保存评级
        const data = {
          rating: row.rating
        };
        
        updateSupplierRegistrationAPI(row.id, data).then(res => {
          if (res.code === 200) {
            this.$message.success('评级保存成功');
            row.editing = false;
          } else {
            this.$message.error(res.message || '评级保存失败');
          }
        }).catch(error => {
          this.$message.error('评级保存失败，请检查网络');
          console.error('保存错误:', error);
        });
      } else {
        // 进入编辑状态
        row.editing = true;
      }
    },
    
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端删除接口
        deleteSupplierRegistrationAPI(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getTableData();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        }).catch(error => {
          this.$message.error('删除失败，请检查网络');
          console.error('删除错误:', error);
        });
      }).catch(() => {});
    },
    
    // 分页 - 每页条数改变
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    
    // 分页 - 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getTableData();
    },
    
    // 获取审批状态文本
    getApprovalStatusText(status) {
      const statusMap = {
        '0': '未审批',
        '1': '审批通过',
        '2': '审批失败'
      };
      return statusMap[status] || '未知';
    },
    
    // 获取审批状态标签类型
    getApprovalStatusType(status) {
      const typeMap = {
        '0': '',
        '1': 'success',
        '2': 'danger'
      };
      return typeMap[status] || '';
    },
    
    // 生成供应商加盟链接和二维码
    generateJoinLink() {
      // 获取当前登录用户信息
      const user = JSON.parse(localStorage.getItem('admin_user') || '{}');
      
      // 生成链接
      const baseUrl = window.location.origin + '/#/channel';
      const params = new URLSearchParams({
        title: (user.companyName || user.username) + '供应商',
        userId: user.id
      });
      this.joinLinkData.url = `${baseUrl}?${params.toString()}`;
      
      // 生成二维码
      this.joinLinkData.qrCode = this.joinLinkData.url;
      
      // 显示对话框
      this.joinLinkDialogVisible = true;
    },
    
    // 复制链接
    copyLink() {
      const input = document.createElement('input');
      input.value = this.joinLinkData.url;
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      this.$message.success('链接已复制到剪贴板');
    }
  }
};
</script>

<style lang="scss" scoped>
.supplier-collection-page {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
      color: #333;
    }
  }
  
  .query-area {
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 20px;
  }
  
  .table-area {
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;
  }
  
  .qrcode-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 0;
  }
  
  .qrcode-image {
    max-width: 200px;
    max-height: 200px;
  }
}
</style>